package com.yonyou.brigade.third_parties.bfjr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.ThirdResult;
import com.yonyou.brigade.third_parties.bfjr.constant.BfjrConstant;
import com.yonyou.brigade.third_parties.bfjr.dao.BfjrUserMapper;
import com.yonyou.brigade.third_parties.bfjr.model.BfjrUser;
import com.yonyou.brigade.third_parties.bfjr.service.IBfjrDeptService;
import com.yonyou.brigade.third_parties.bfjr.service.IBfjrPublicService;
import com.yonyou.brigade.third_parties.bfjr.service.IBfjrUserService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.CompareUtils;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BfjrUserServiceImpl extends ServiceImpl<BfjrUserMapper,BfjrUser> implements IBfjrUserService {

    private static Logger logger = LoggerFactory.getLogger(BfjrUserServiceImpl.class);

    @Value("${bfjr.url.employeeAdd}")
    private String empAddUrl;

    @Value("${bfjr.url.employeeEdit}")
    private String empEditUrl;

    @Autowired
    private IBriChannelService briChannelService;

    @Autowired
    private IBfjrUserService bfjrUserService;

    @Autowired
    private IUserCenterService userCenterService;

    @Autowired
    private PropUtil propUtil;

    @Autowired
    private IBfjrPublicService bfjrPublicService;

    @Autowired
    private IBfjrDeptService bfjrDeptService;

    private static final String[] compareFields = {"expEmpId", "empName", "empExpDeptId", "traPlcName", "mobileNo", "uEmail"};



    @Override
    public void syncBfjrUserList(List<UcUserDto> ucUserDto, BriChannel briChannel, String tenant) {
        for (UcUserDto userDto : ucUserDto) {
            syncUser(tenant, userDto.getPhone(), userDto, briChannel);
        }
    }

    public void syncUser(String tenant, String phone, UcUserDto ucUserDto, BriChannel briChannel){
        BfjrUser bfjrUser = ucUserConvert2BfjrUser(ucUserDto, tenant,briChannel);
        Wrapper<BfjrUser> wrapper = new EntityWrapper<>();
        wrapper.eq("tenant", tenant);
        wrapper.eq("mobileNo", phone);
        List<BfjrUser> bfjrUserList = bfjrUserService.selectList(wrapper);

        //判断是否已经同步过，新增或修改
        if (bfjrUserList != null && bfjrUserList.size() > 0){
            //如果已经同步过，检查信息是否有变化，如果有变化则更新
            Map<String, String> compareMap = new HashMap<>();

            if (compareFields != null && compareFields.length > 0) {
                for (int i = 0; i < compareFields.length; i++) {
                    //此处只需要key值
                    compareMap.put(compareFields[i], "");
                }
            }
            Map<String, Object> compareResult = CompareUtils.getModifyContent(bfjrUserList.get(0), bfjrUser, compareMap);
            if (compareResult != null && compareResult.size() > 0) {
                //更新已经同步过的用户信息
                ThirdResult thirdResult = this.syncUser(bfjrUser, briChannel, BfjrConstant.EMPLOYEE_OPERATION_TYPE_EDIT);
                if (thirdResult.getSuccess()){
                    bfjrUser.setId(bfjrUserList.get(0).getId());
                    this.baseMapper.updateById(bfjrUser);
                }
            }
        }else {
            //未同步过，新增
            ThirdResult thirdResult = this.syncUser(bfjrUser, briChannel, BfjrConstant.EMPLOYEE_OPERATION_TYPE_ADD);
            if (thirdResult.getSuccess()){
                this.baseMapper.insert(bfjrUser);
            }
        }
    }



    @Override
    public ThirdResult syncUser(BfjrUser bfjrUser, BriChannel briChannel, String operationType) {
        JSONObject config = JSONObject.parseObject(briChannel.getConfig());
        String appId = config.getString("appId");
        String url = "" ;
        if (BfjrConstant.EMPLOYEE_OPERATION_TYPE_ADD.equals(operationType)) {
            url = empAddUrl;
        } else if (BfjrConstant.EMPLOYEE_OPERATION_TYPE_EDIT.equals(operationType)) {
            url = empEditUrl;
        }
        JSONObject requestParam = convertRequestParam(bfjrUser, appId);
        logger.info("同步北方假日用户" + requestParam.toJSONString());
        String strResult = HttpClientUtil.doPostJsonForm(url, requestParam.toJSONString());
        logger.info("同步北方假日用户结果" + strResult);
        if (StringUtil.isNotEmpty(strResult)){
            JSONObject rs = JSONObject.parseObject(strResult);
            if ("0".equals(rs.getString("ret"))){
                return new ThirdResult(true, rs.getString("msg") );
            }else {
                return new ThirdResult(false, rs.getString("msg") );
            }
        }
        return new ThirdResult(false, strResult );
    }
    /**
     * 拼装请求参数
     * @param bfjrUser
     * @param appId
     * @return
     */
    private JSONObject convertRequestParam(BfjrUser bfjrUser, String appId){
        JSONObject param = new JSONObject();
        param.put("appId", appId);
        param.put("expEmpId", bfjrUser.getExpEmpId());
        param.put("empName",bfjrUser.getEmpName());
        param.put("empGender",bfjrUser.getEmpGender());
        param.put("expEmpDeptId",bfjrUser.getExpEmpDeptId());
        param.put("traPlcName",bfjrUser.getTraPlcName());
        param.put("mobileNo",bfjrUser.getMobileNo());
        return param;
    }



    @Override
    public BfjrUser ucUserConvert2BfjrUser(UcUserDto ucUserDto, String tenant,BriChannel briChannel){
        JSONObject config = JSONObject.parseObject(briChannel.getConfig());
        String appId = config.getString("appId");
        BfjrUser bfjrUser = new BfjrUser();
        bfjrUser.setExpEmpId(ucUserDto.getPersonCode());
        bfjrUser.setEmpName(ucUserDto.getUserName());
        bfjrUser.setEmpGender("0");
        bfjrUser.setExpEmpDeptId(ucUserDto.getOrgPk());
        if (1 == briChannel.getSyncRank()) {
            bfjrUser.setTraPlcName(ucUserDto.getPostName());
        } else if (2 == briChannel.getSyncRank()) {
            bfjrUser.setTraPlcName(ucUserDto.getRankName());
        }
        bfjrUser.setMobileNo(ucUserDto.getPhone());
        bfjrUser.setTenant(tenant);
        bfjrUser.setAppId(appId);
        return bfjrUser;
    }



    @Override
    public String loginUrl(String tenant, String org, String phone, String pageType, String pcOrH5, String jsonExt) {
        BriChannel briChannel = briChannelService.getEnableChannelByTenantAndOrgAndChannelAndOpenType(tenant,org, ChannelEnum.BFJR.getName(), 2);
        if(briChannel==null) {
            //没有开通北方假日
            return propUtil.getNO_ACCESS_URL();
        }
        UcUserDto ucUser = userCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
        if (ucUser == null){
            return propUtil.getNO_ACCESS_URL();
        }
        JSONObject config = JSONObject.parseObject(briChannel.getConfig());

        if (BriChannel.SYNCORGDEPT.equals(briChannel.getSyncOrgDept())) {
            //同步一级部门
            bfjrDeptService.sysOrgDept(tenant,ucUser.getOrgPk(), ucUser.getOrgName(), config);
        }

        //同步用户
        if (BriChannel.SYNCUSER.equals(briChannel.getSyncUser())){
            syncUser(tenant, phone, ucUser, briChannel);
        }

         String rsUrl = bfjrPublicService.ssoLogin(ucUser.getPersonCode(),config,pcOrH5);


        return rsUrl;
    }

}
